package com.onlyphoto.onlymall.mvp.view.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.onlyphoto.onlymall.R
import com.onlyphoto.onlymall.bean.response.RefundReasonBean
import java.util.ArrayList

/**
 * Created by gaochujia on 2019-08-27.
 */

class OptionAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private var mList = arrayListOf<RefundReasonBean>()
    private var listener: OnItemClickListener? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val item = LayoutInflater.from(parent.context).inflate(
                R.layout.item_option, parent, false)
        return OptionItemHolder(item)
    }

    override fun getItemCount(): Int {
        return mList.size
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        (holder as OptionItemHolder).loadData(mList[position])
        holder.itemView.setOnClickListener{
            mList[position].isSelected = !mList[position].isSelected

            if (mList[position].isSelected) {
                listener?.click(mList[position].id, mList[position].name)
            } else {
                listener?.click(0, "")
            }
            notifyItemChanged(position)
            for ((index, bean) in mList.withIndex()) {
                if (index != position && bean.isSelected) {
                    bean.isSelected = false
                    notifyItemChanged(index)
                }
            }
        }
    }

    fun setItemData(list: ArrayList<RefundReasonBean>) {
        this.mList = list
        notifyDataSetChanged()
    }

    class OptionItemHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        var check: ImageView? = null
        var name: TextView? = null

        init {
            check = itemView.findViewById(R.id.check)
            name = itemView.findViewById(R.id.name)
        }

        fun loadData(bean: RefundReasonBean) {
            name?.text = bean.name
            if (bean.isSelected) {
                check?.setImageDrawable(ContextCompat.getDrawable(itemView.context, R.drawable.checked))
            } else {
                check?.setImageDrawable(ContextCompat.getDrawable(itemView.context, R.drawable.check_normal))
            }
        }
    }

    fun setOnItemClickListener(listener: OnItemClickListener){
        this.listener = listener
    }

    interface OnItemClickListener{
        fun click(id: Int, name: String)
    }
}